// 导入数据库
const db = require('../db')
const bcrypt = require('bcryptjs')
    //获取用户信息
exports.getUserInfo = (req, res) => {
        const sql = 'select * from stu_users where id=?'
        db.query(sql, req.auth.id, (err, results) => {
            if (err) return res.sd(err.message)
            if (results.length !== 1) return res.sd('获取用户信息失败')
            res.send({
                status: 0,
                message: '获取用户信息成功',
                data: results[0]
            })
        })
    }
    //更新用户信息
exports.updateUserInfo = (req, res) => {
        const sql = `select * from  stu_users where id=?`
        db.query(sql, req.auth.id, (err, results) => {
            if (err) return res.sd(err.message)
            if (results.length !== 1) return res.sd('用户不存在')

            const sql = `update stu_users set ? where id=?`

            db.query(sql, [req.body, req.auth.id], (err, results) => {

                if (err) return res.sd(err.message)
                if (results.affectedRows !== 1) return res.sd('更新用户信息失败')
                res.send({
                    // status: 1
                    status: 0,
                    message: '更新用户成功'
                })
            })
        })
    }
    //更新密码
exports.updatePassword = (req, res) => {
        const sql = `select * from stu_users where id=?`
        db.query(sql, req.auth.id, (err, results) => {
            if (err) return res.sd(err.message)
            if (results.length !== 1) return res.sd('用户不存在')
            const comparePwd = bcrypt.compareSync(req.body.oldPwd, results[0].password)
            if (!comparePwd) return res.sd('原密码错误')
            const newPwd = bcrypt.hashSync(req.body.newPwd, 10)
            const sql = `update stu_users set ? where id=?`
            db.query(sql, [{ password: newPwd }, req.auth.id], (err, results) => {
                if (err) return res.sd(err.message)
                if (results.affectedRows !== 1) return res.sd('修改密码失败')
                res.send({
                    status: 0,
                    message: '修改密码成功'
                })
            })
        })
    }
    //修改头像
exports.updateAvater = (req, res) => {
    const sql = `select * from stu_users where id=?`
    db.query(sql, req.auth.id, (err, results) => {
        if (err) return res.sd(err.message)
        if (results.length !== 1) return res.sd('用户不存在')
        const sql = `update stu_users set? where id=?`
        db.query(sql, [{ avater: req.body.avater }, req.auth.id], (err, results) => {
            if (err) return res.sd(err.message)
            if (results.affectedRows !== 1) res.sd('更新头像失败')
            res.send({
                status: 0,
                message: '更新头像成功'
            })
        })
    })
}